--[[
Author: your name
Date: 2020-10-15 15:10:06
LastEditTime: 2020-10-15 15:33:25
LastEditors: your name
Description: In User Settings Edit
FilePath: \Lua\Main.lua
--]]
--[[主入口函数。从这里开始lua逻辑
local breakSocketHandle,debugXpCall = require("LuaDebugjit")("localhost",7003)
local timer = Timer.New(function() 
breakSocketHandle() end, 1, -1, false)
timer:Start();]]
package.cpath = package.cpath .. ';C:/Users/tengxiaoyang/AppData/Roaming/JetBrains/IdeaIC2020.2/plugins/intellij-emmylua/classes/debugger/emmy/windows/x64/?.dll'
local dbg = require('emmy_core')
dbg.tcpListen('localhost', 9968)
function Main()
	print("logic start");
end

--场景切换通知
function OnLevelWasLoaded(level)
	--collectgarbage("collect")
	--Time.timeSinceLevelLoad = 0
end

function OnApplicationQuit()
end

--function LuaGC() 
--	print("LuaGC count:", collectgarbage("count"))
--	collectgarbage("collect")
--    Util.PrintLuaObject();
--end

function NetDataRecv( msgid, p )
    NetMsgDecoder.msgHandler(msgid, p)
end

-------------GC相关
GlobalFrameCount = GlobalFrameCount or 1
GlobalNowTime = GlobalNowTime or 0
local LastFPSTime = 0
local need_force_gc = false
local MAX_LUA_OBJECT_COUNT_LIMIT = 2800
local MIN_LUA_OBJECT_COUNT_LIMIT = 1500
local TimeFrameCount = 0
local function LuaGCFunc()
    TimeFrameCount = TimeFrameCount + 1
    local current_lua_obj_count =  Util.GetLuaObjectCount()
    if current_lua_obj_count >  MAX_LUA_OBJECT_COUNT_LIMIT   then
        need_force_gc = true
    end
    if need_force_gc and GlobalFrameCount % 2 == 0  then
        local gc_finish = collectgarbage("step",40)
        if Util.GetLuaObjectCount() < MIN_LUA_OBJECT_COUNT_LIMIT then
            gc_finish = true
        end
        if gc_finish  then
            need_force_gc = false
        end
        return
    end
    local dt = GlobalNowTime - LastFPSTime
    local now_fps = TimeFrameCount / dt
    TimeFrameCount = 0
    LastFPSTime = GlobalNowTime
    if now_fps > UnityEngine.Application.targetFrameRate * 0.85 then 
        collectgarbage("step", 30)	
    end
end
-------------end

-- Update
function LuaUpdate( deta_time ) 
	GlobalFrameCount = GlobalFrameCount + 1
	GlobalNowTime = UnityEngineTime.realtimeSinceStartup
	LuaGCFunc()
end  